package com.nhc.activity_fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.astrob.activitys.AppContext;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.dbmodel.WayPoint;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.model.Entry;
import zuo.biao.library.util.Log;

public class SelectIconActivity extends BaseActivity {
    private final String TAG = "SelectIconActivity";

    public static final String INTENT_ICON_TYPE = "INTENT_ICON_TYPE";
    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context, int icontype) {
        return new Intent(context, SelectIconActivity.class)
                .putExtra(INTENT_ICON_TYPE, icontype);
    }
    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public Activity getActivity() {
        return this;
    }

    int _icontype = 0;//0-航点 1-车标

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.selecticon_activity);

        _icontype = getIntent().getIntExtra(INTENT_ICON_TYPE, _icontype);
        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>
    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private GridView lvIconGird;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreate方法内调用
        autoSetTitle();//自动设置标题为上个Activity传入的INTENT_TITLE

        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        lvIconGird = (GridView) findViewById(R.id.lvIconGird);
//        iv_check.setTypeface(AppContext.getInstances().getIconfont());
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    //示例代码<<<<<<<<
    private GridAdapter adapter;
    //示例代码>>>>>>>>

    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new GridAdapter(context);
            lvIconGird.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> list;

    protected List<Entry<Integer, String>> getList() {
        list = new ArrayList<Entry<Integer, String>>();
        int size = 2;
        if (_icontype == 0) {
            size = WayPoint.TYPE_IDS_L.length;
        }
        for (int i = 0; i < size; i++) {
            list.add(new Entry<Integer, String>(i, ""));
        }
        return list;
    }

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreateView方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        showProgressDialog(R.string.loading);

        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                list = getList();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList(list);
                    }
                });
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用
        lvIconGird.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                doFounc(adapter.getItem(position).getKey());
            }
        });
        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    private void doFounc(Integer gridIndex) {
//        showShortToast("选择了 " + WayPoint.TYPE_IDS[gridIndex]);
        setResult(gridIndex);
        finish();
    }

    @Override
    public void onReturnClick(View v) {
        setResult(-1);
        finish();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            default:
                adapter.notifyDataSetChanged();
                break;
            case KeyEvent.KEYCODE_BACK:
                setResult(-1);
                finish();
                return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    public class GridAdapter extends BaseAdapter<Entry<Integer, String>> {
        private final String TAG = "GridAdapter";

        public GridAdapter(Activity context) {
            this(context, R.layout.more_grid_item);
        }

        public GridAdapter(Activity context, int layoutRes) {
            super(context);
            setLayoutRes(layoutRes);
        }

        private int layoutRes;//item视图资源

        public void setLayoutRes(int layoutRes) {
            this.layoutRes = layoutRes;
        }

        private boolean hasName = false;//是否显示名字

        public GridAdapter setHasName(boolean hasName) {
            this.hasName = hasName;
            return this;
        }

        private boolean hasCheck = false;//是否使用标记功能

        public GridAdapter setHasCheck(boolean hasCheck) {
            this.hasCheck = hasCheck;
            return this;
        }

        //item标记功能，不需要可以删除<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        private HashMap<Integer, Boolean> hashMap;//实现选中标记的列表，不需要可以删除。这里可用List<Integer> checkedList代替

        public boolean getItemChecked(int position) {
            if (hasCheck == false) {
                Log.e(TAG, "<<< !!! hasCheck == false  >>>>> ");
                return false;
            }
            return hashMap.get(position);
        }

        public void setItemChecked(int position, boolean isChecked) {
            if (hasCheck == false) {
                Log.e(TAG, "<<< !!! hasCheck == false >>>>> ");
                return;
            }
            hashMap.put(position, isChecked);
            notifyDataSetChanged();
        }
        //item标记功能，不需要可以删除>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


        public int selectedCount = 0;

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        layoutRes, parent, false);
            }

            ImageView iv_item = BaseViewHolder.get(convertView, R.id.iv_item);
            TextView tv_item = BaseViewHolder.get(convertView, R.id.tv_item);
            tv_item.setVisibility(View.GONE);
            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            TextView tv_focus = BaseViewHolder.get(convertView, R.id.tv_focus);
            iv_check.setTypeface(AppContext.getInstances().getIconfont());

            final Entry<Integer, String> kvb = getItem(position);
            int gridIndex = kvb.getKey();

            int resId = 0;
            if (_icontype == 0) {
                if (gridIndex < 0 || gridIndex >= WayPoint.TYPE_IDS_L.length) {
                    gridIndex = 0;
                }
                resId = WayPoint.TYPE_IDS_L[gridIndex];
            } else if (_icontype == 1) {
                if (gridIndex == 0) {
                    resId = R.drawable.i3_car00;
                } else if (gridIndex == 1) {
                    resId = R.drawable.i3_car3d;
                }
            }

            iv_item.setImageResource(resId);

            if (hasCheck) {
                iv_check.setVisibility(View.VISIBLE);
                iv_check.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setItemChecked(position, !getItemChecked(position));
                    }
                });
            }

            int select = lvIconGird.getSelectedItemPosition();
            if (select == position && SysUtils.getInstance().is240x320) {
                tv_focus.setVisibility(View.VISIBLE);
            } else {
                tv_focus.setVisibility(View.GONE);
            }

            return convertView;
        }

        /**
         * 刷新列表
         *
         * @param list
         */
        @Override
        public synchronized void refresh(List<Entry<Integer, String>> list) {
            if (list != null && list.size() > 0) {
                initList(list);
            }
            if (hasCheck) {
                selectedCount = 0;
                for (int i = 0; i < this.list.size(); i++) {
                    if (getItemChecked(i) == true) {
                        selectedCount++;
                    }
                }
            }
            notifyDataSetChanged();
        }

        /**
         * 标记List<String>中的值是否已被选中。
         * 不需要可以删除，但“this.list = list;”这句
         * 要放到constructor【这个adapter只有ModleAdapter(Context context, List<Object> list)这一个constructor】里去
         *
         * @param list
         * @return
         */
        @SuppressLint("UseSparseArrays")
        private void initList(List<Entry<Integer, String>> list) {
            this.list = list;
            if (hasCheck) {
                hashMap = new HashMap<Integer, Boolean>();
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        hashMap.put(i, false);
                    }
                }
            }
        }

    }

}
